/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/// <reference path="../base/lcc.ts" />
/// <reference path="../utils/js.ts" />

namespace lcc {

const TAG = "lcc/load/load-manager.ts";

/**
 * @zh
 * 模块资源
 */
export interface ModuleAsset {
	/**
	 * @zh
	 * 模块名
	 */
	moduleName:string;

	/**
	 * @zh
	 * 资源路径
	 */
	assetPaths:string[];
}

/**
 * @zh
 * 资源页
 */
export interface AssetsPage {
	/**
	 * @zh
	 * 总比重
	 */
	totalWeight:number;

	/**
	 * @zh
	 * 资源表
	 */
	assets:{[key:string]:string[]};
}

/**
 * @zh
 * 加载管理器<br/>
 * 可以管理框架内资源的加载
 */
export class LoadManager extends __cc__.EventTarget {
	/**
	 * @zh
	 * 管理器实例
	 */
	private static _instance:LoadManager;

	/**
	 * @zh
	 * 获得单例对象
	 */
	public static getInstance() : LoadManager  {
		if(!LoadManager._instance){
			LoadManager._instance = new LoadManager();
		}
		return LoadManager._instance;
	}

	/**
	 * @zh
	 * 模块比重
	 */
	private _moduleWeights:{[key:string]:number} = utils.js.createMap();

	/**
	 * @zh
	 * 资源加载器
	 */
	private _assetLoaders:{[key:string]:AssetsLoader} = utils.js.createMap();

	/**
	 * @zh
	 * 资源页表
	 */
	private _assetPages:{[key:string]:AssetsPage} = utils.js.createMap();

	/**
	 * @zh
	 * 当前资源页
	 */
	private _nowPage:string = null;

	/**
	 * @zh
	 * 设置模块比重
	 * 
	 * @param mtype - 模块类型
	 * @param weight - 模块比重
	 */
	public setModuleWeight(mtype:string, weight:number){
		this._moduleWeights[mtype] = weight;
	}

	/**
	 * @zh
	 * 获得模块比重
	 * 
	 * @param ntype - 模块类型 
	 */
	public getModuleWeight(mtype:string){
		return this._moduleWeights[mtype] || 1;
	}

	/**
	 * @zh
	 * 设置资源加载器
	 * 
	 * @param mtype - 模块类型
	 * @param loader - 加载器对象
	 */
	public setAssetLoader(mtype:string, loader:AssetsLoader){
		this._assetLoaders[mtype] = loader;
	}
	
	/**
	 * @zh
	 * 获得资源加载器
	 * 
	 * @param mtype - 模块类型
	 */
	public getAssetLoader(mtype:string){
		return this._assetLoaders[mtype];
	}

	/**
	 * @zh
	 * 设置资源页
	 * 
	 * @param pname - 页名称
	 * @param moduleAsset - 资源参数数组
	 */
	public async setAssetsPage(pname:string, moduleAssets:ModuleAsset|ModuleAsset[]){
		if(!(moduleAssets instanceof Array)){
			moduleAssets = [ moduleAssets ];
		}
		let totalWeight = 0;
		let assets:{[key:string]:string[]} = utils.js.createMap();
		for(let moduleconf of moduleAssets){
			let weight = this.getModuleWeight(moduleconf.moduleName);
			totalWeight += weight * moduleconf.assetPaths.length;
			assets[moduleconf.moduleName] = moduleconf.assetPaths;
		}
		this._assetPages[pname] = {
			totalWeight : totalWeight,
			assets : assets,
		};
	}
	
	/**
	 * @zh
	 * 加载资源页
	 * 
	 * @param pname - 页名称
	 * @param progress - 进度
	 */
	public async loadPage(pname:string, progress = (p:number)=>{}){
		progress(0);
		if(this._nowPage != pname){
			let lastpage = this._assetPages[this._nowPage];
			this._nowPage = pname;
			let page = this._assetPages[pname];
			if (!page){
				return __cc__.error(TAG, `assets page ${pname} not found`);
			}
			let lastassets = lastpage ? lastpage.assets : utils.js.createMap();

			// 释放未引用节点
			for(let node of Object.keys(lastassets).filter((s)=>{ return page.assets[s] == null; })){
				let loader = this.getAssetLoader(node);
				if(loader){
					loader.releaseAssets(lastassets[node]);
				}
			}
			
			let nowweight = 0;
			for (let node in page.assets){
				let loader = this.getAssetLoader(node);
				if(!loader){
					return __cc__.error(TAG, `assets loader ${node} not found`);
				}
				let weight = this.getModuleWeight(node);
				let asset = page.assets[node];
				let lastasset = lastassets[node] || [];

				// 释放未引用资源
				let releases = lastasset.filter((s)=>{ return asset.indexOf(s) == -1; });
				loader.releaseAssets(releases);

				// 加载新资源
				let loads = asset.filter((s)=>{ return lastasset.indexOf(s) == -1 });
				let loadweight = weight * loads.length;
				await loader.loadAssets(loads,(p:number)=>{
					progress((nowweight + loadweight * p) / page.totalWeight);
				});
				nowweight += loadweight;
				progress(nowweight / page.totalWeight);
			}
		}
		progress(1);
	}
};

/**
 * @zh
 * 加载管理器对象
 */
export const loadMgr = LoadManager.getInstance();

}
